package com.pengpai.pangucms.global;

import com.pengpai.pangucms.utils.R;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author Lijunjie
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     *  违反唯一性约束
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public R handleDuplicateKeyException(DuplicateKeyException e, HttpServletRequest request) {
        log.error("请求地址'{}',发生系统异常.", request.getRequestURI(), e);
        return R.fail(R.HTTPStatusCode.ERROR,"数据违反唯一性约束！");
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public R handleException(AccessDeniedException e, HttpServletRequest request) {
        log.error("请求地址'{}',发生系统异常.", request.getRequestURI(), e);
        return R.fail(R.HTTPStatusCode.FORBIDDEN);
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e, HttpServletRequest request) {
        log.error("请求地址'{}',发生系统异常.", request.getRequestURI(), e);
        return R.fail(R.HTTPStatusCode.ERROR);
    }


}
